// utils/subscribeAuth.js
import { ref } from 'vue'

// 全局授权状态
const globalAuthState = ref({
  hasSubscribed: false,
  rememberChoice: false,
  isCoolingDown: false
})

// 授权配置
const authConfig = {
  templateIds: ['8BYCmgqMs93PA1OxJao3t5VxI-6XxBiR_jKuUVHqIWQ'],
  coolDownTime: 5000,
  enableTransparentAuth: true
}

// 创建授权实例
export const createSubscribeAuth = (config = {}) => {
  const finalConfig = { ...authConfig, ...config }
  
  return {
    // 触发授权
    async trigger() {
      if (globalAuthState.value.isCoolingDown) {
        throw new Error('授权请求过于频繁')
      }
      
      // 检查本地存储
      const storedChoice = uni.getStorageSync('user_subscribe_choice')
      const storedRemember = uni.getStorageSync('subscribe_remember_choice')
      
      if (storedChoice === 'accepted' && storedRemember) {
        return { success: true, type: 'silent' }
      }
      
      if (storedChoice === 'rejected' && storedRemember) {
        throw new Error('用户已拒绝订阅')
      }
      
      // 设置冷却
      globalAuthState.value.isCoolingDown = true
      setTimeout(() => {
        globalAuthState.value.isCoolingDown = false
      }, finalConfig.coolDownTime)
      
      try {
        const result = await requestSubscribe(finalConfig.templateIds)
        return result
      } catch (error) {
        throw error
      }
    },
    
    // 重置授权
    reset() {
      uni.removeStorageSync('user_subscribe_choice')
      uni.removeStorageSync('subscribe_remember_choice')
      globalAuthState.value.hasSubscribed = false
      globalAuthState.value.rememberChoice = false
    },
    
    // 获取状态
    getState() {
      return { ...globalAuthState.value }
    }
  }
}

// 请求订阅消息
const requestSubscribe = (tmplIds) => {
  return new Promise((resolve, reject) => {
    uni.requestSubscribeMessage({
      tmplIds,
      success: (res) => {
        const allAccepted = tmplIds.every(tmplId => res[tmplId] === 'accept')
        if (allAccepted) {
          uni.setStorageSync('user_subscribe_choice', 'accepted')
          globalAuthState.value.hasSubscribed = true
          resolve({ success: true, result: res })
        } else {
          uni.setStorageSync('user_subscribe_choice', 'rejected')
          globalAuthState.value.hasSubscribed = false
          resolve({ success: false, result: res })
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 默认导出
export default {
  install: (app, options) => {
    app.config.globalProperties.$subscribeAuth = createSubscribeAuth(options)
  }
}